//
//  CZEmoticonModel.swift
//  表情键盘新工程-74.准备
//
//  Created by itcast on 16/5/22.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

/*
    保存对象
        1.实现NSCoding
        2.调用对应的方法
*/

/// 表情模型,图片表情模型和Emoji表情模型
class CZEmoticonModel: NSObject, NSCoding {
    
    /// 模型所在文件夹名称
    var id: String

    /// chs, 网络传输使用
    var chs: String?
    
    /// png, 客户端显示的图片
    var png: String? {
        didSet {
            // 根据图片名称拼接图片完整路径
            // fullPngPath = Emoticons.bundle/id/png
            fullPngPath = emoticonBundlePath + "/" + id + "/" + png!
        }
    }
    
    /// 图片全路径,每次运行沙盒的路径都会发生改变
    var fullPngPath: String?
    
    /// code, emoji的16进制字符串
    var code: String? {
        didSet {
            // 将code转成emoji
            // 扫描器
            let scanner = NSScanner(string: code!)
            
            var result: UInt32 = 0
            // 扫描16进制的的字符串为UInt32
            scanner.scanHexInt(&result)
            
            let c = Character(UnicodeScalar(result))
            
            emoji = String(c)
        }
    }
    
    /// emoji
    var emoji: String?
    
    /// 字典转模型
    init(dict: [String: String], id: String) {
        self.id = id
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    // 字典中的key在模型中没有对应的属性
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    // 打印方法
    override var description: String {
        get {
            return "\n\t\t 表情模型: chs: \(chs), png: \(png), code: \(code)"
        }
    }
    
    // MARK: - 实现NSCoding协议方法
    required init?(coder aDecoder: NSCoder) {
        id = aDecoder.decodeObjectForKey("id") as? String ?? ""
        chs = aDecoder.decodeObjectForKey("chs") as? String
        png = aDecoder.decodeObjectForKey("png") as? String
//        fullPngPath = aDecoder.decodeObjectForKey("fullPngPath") as? String
        code = aDecoder.decodeObjectForKey("code") as? String
        emoji = aDecoder.decodeObjectForKey("emoji") as? String
        
        // 在init构造函数里面给属性赋值,不会触发 didSet
        // 重新拼接fullPngPath
        if let p = png {
            fullPngPath = emoticonBundlePath + "/" + id + "/" + p
        }
    }
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(id, forKey: "id")
        aCoder.encodeObject(chs, forKey: "chs")
        aCoder.encodeObject(png, forKey: "png")
//        aCoder.encodeObject(fullPngPath, forKey: "fullPngPath")
        aCoder.encodeObject(code, forKey: "code")
        aCoder.encodeObject(emoji, forKey: "emoji")
    }
}
